import { Channel, Article } from '@/types/data'
import { HomeAction } from '@/types/store'

type HomeType = {
  userChannels: Channel[],
  allChannels: Channel[],
  active: number,
  channelArticles: {
    [key: number]: {
      timestamp: number,
      articles: Article[]
    }
  }
}
const initState: HomeType = {
  userChannels: [],
  allChannels: [],
  active: 0,  // 默认高亮
  channelArticles: {}
}
export default function home(state = initState, action: HomeAction) {
  if (action.type === 'home/saveUserChannels') {
    return {
      ...state,
      userChannels: action.payload
    }
  }
  if (action.type === 'home/saveAllChannels') {
    return {
      ...state,
      allChannels: action.payload
    }
  }
  if (action.type === 'home/changeActive') {
    return {
      ...state,
      active: action.payload
    }
  }
  if (action.type === 'home/saveChannelArticles') {
    const {
      channel_id,
      timestamp,
      articles
    } = action.payload
    const old = state.channelArticles[channel_id]?.articles || []
    return {
      ...state,
      channelArticles: {
        // 需要追加数据
        ...state.channelArticles,
        [channel_id]: {
          timestamp: +timestamp,
          articles: [...old, ...articles]
        }
      }
    }
  }
  if (action.type === 'home/saveNewChannelArticles') {
    const { channel_id, timestamp, articles } = action.payload
    return {
      ...state,
      channelArticles: {
        // 需要追加数据
        ...state.channelArticles,
        [channel_id]: {
          timestamp: +timestamp,
          articles: [...articles]
        }
      }
    }
  }
  return state
}